import os

from src.api.https import SUCCESS, FAIL, fail_api, success_api, table_api
from flask import Blueprint, request, session

from src.utils.check_require import login_required
from src.utils.picture_tool import PictureTool
from src.utils.res_tool import ResTool

from src.init.init_path import PATH, AVATAR_PATH, BASE_PATH
from src.model.PictureModel import PictureModel
from src.model.AritcleModel import ArticleModel
from src.utils.info_tool import getmessage
from src.utils.user_tool import UserTool

# 创建蓝图
res_api = Blueprint("resource", __name__, url_prefix='/api/res')

res_tool = ResTool()
ptool = PictureTool()


@res_api.post('/avatar')
@login_required
def update_avatar():
    # 更新用户头像
    file = request.files.getlist('file')
    uid = str(session['uid'])

    # 首先查看用户头像是否存在，存在则删除原图片，上传新头像进行更新，否则仅上传新头像
    filetype = file[0].filename.split(".")[-1]

    url = os.path.join(BASE_PATH + AVATAR_PATH, uid + "." + filetype)
    purl = os.path.join("imgresource" + AVATAR_PATH, uid + "." + filetype)
    if os.path.exists(url) and os.path.isfile(url):
        try:
            os.remove(url)  # 删除文件
            print(f"文件 {url} 已成功删除")
        except Exception as e:
            print(f"删除文件时出错: {e}")

    file[0].save(url)
    data = {"avatar": purl}
    utool = UserTool()
    utool.update(data, uid)
    data = {"avatar": "http://" + request.host + "/" + purl}
    return table_api(data=data)


@res_api.post('/upload')
@login_required
def up_picture():
    # 编辑过程中上传图片
    global ptool
    aid = int(request.form.get('aid'))
    file = request.files.get('file')
    msg = ptool.init(aid, file)
    if msg["pid"] == 0:
        return fail_api(msg["err"])
    msg["purl"] = "http://" + request.host + "/" + msg["purl"]
    return success_api(data=msg)